/*************************************************************************
	> File Name: db.c
	> Author: 
	> Mail: 
	> Created Time: 2019年02月28日 星期四 11时22分27秒
 ************************************************************************/

#include<stdio.h>
#include"common.h"
#include "db.h"

struct sqlite3 *g_db = NULL;

//初始化数据
long InitConnections(void)
{
    if(NULL != g_db)
    {
        if(DB_ERROR_OK != CloseConnections(g_db))
        {
            return(DB_ERROR_OK != CloseConnections(g_db));
        }
        g_db = NULL;
        return DB_ERROR_OK;
    }
}
long OpenConnection(void)
{
    if(DB_ERROR_OK != InitConnections())
    {
        printf("invoke InitConnections function error!\n");
        return -1;
    }
    int iResult = sqlite3_open("/try.db",&g_db);
    if(SQLITE_OK != iResult)
    {
        return DB_ERROR_FAILURE;
    }
    return DB_ERROR_OK;
}
//关闭数据库
long CloseConnections(sqlite3 *pDB)
{
    if(NULL == g_db)
    {
        return DB_ERROR_OK;
    }
    int iResult = sqlite3_close(g_db);
    if(SQLITE_OK != iResult)
    {
        return DB_ERROR_FAILURE;
    }
    g_db = NULL;
    return DB_ERROR_OK;
}
int Mysqlite_in_operar(char *ptime,char *ptem,char *phyg,char *psmog)
{
    char *pErrMsg = NULL;
    char TEMP[100000];
    //sprintf(TEMP="temperature is ='%s'",ptem);
    int iResult = sqlite3_exec(g_db,TEMP,0,0,&pErrMsg);
    if(SQLITE_OK != iResult)
    {
        printf("更新载入信息失败： %s\n",pErrMsg);
    }
    sprintf(TEMP,"insert into stock record(time,temperature,hygrometer,smog)value('%s','%s','%s','%s')",ptime,ptem,phyg,psmog);
    iResult = sqlite3_exec(g_db,TEMP,0,0,&pErrMsg);
    if(SQLITE_OK != iResult)
    {
        printf("记录表添加信息失败%s\n",pErrMsg);
        return 1;
    }
    sqlite3_free(pErrMsg);
    return 2;
}
int Mysqlite_out_oper(char *ptime,char *ptem,char *phyg,char *psmog)
{
    char *pErrMsg = NULL;
    char TEMP[10000];
    //sprintf(TEMP,"")
    int iResult = sqlite3_exec(g_db,TEMP,0,0,&pErrMsg);
    sqlite3_free(pErrMsg);
    sprintf(TEMP,"insert into stock record(time,temperature,hygrometer,smog)value('%s','%s','%s','%s')",ptime,ptem,phyg,psmog);
    if(SQLITE_OK != iResult)
    {
        printf("更新载入信息失败：%s\n",pErrMsg);
    }

    sqlite3_free(pErrMsg);
    return in_out_ok;
}
